package cn.bbstone.pisces2.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetUtil {
	private static Logger log = LoggerFactory.getLogger(NetUtil.class);
	
	public static String getLocalHostAddress() {
		try {
			InetAddress candidateAddress = null;
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface iface = networkInterfaces.nextElement();
				// 该网卡接口下的ip会有多个，也需要一个个的遍历，找到自己所需要的
				for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
					InetAddress inetAddr = inetAddrs.nextElement();
					// 排除loopback回环类型地址（不管是IPv4还是IPv6 只要是回环地址都会返回true）
					if (!inetAddr.isLoopbackAddress()) {
						if (inetAddr.isSiteLocalAddress()) {
							return inetAddr.getHostAddress();
						}
						// 若不是site-local地址 那就记录下该地址当作候选
						if (candidateAddress == null) {
							candidateAddress = inetAddr;
						}
					}
				}
			}
			// 如果除了loopback回环地之外无其它地址了，那就回退到原始方案吧
			InetAddress finalInetAddress = candidateAddress == null ? InetAddress.getLocalHost() : candidateAddress;
			return finalInetAddress.getHostAddress();
		} catch (Exception e) {
			log.error("get local host address error.", e);
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println(NetUtil.getLocalHostAddress());
	}

}
